<?php   
      /* 
      Plugin Name: mf_timetable
      Plugin URI: http://mildfuzz.com
      Description: Plugin for creating admin controllable timetables 
      Author: J. Farrow
      Version: 0.1 
     Author URI: http://www.mildfuzz.com
      */  
 
?>
<?php

//-----DEBUG---/
//ini_set('display_errors', 'On');
//error_reporting(E_ALL);

function mf_timetable_css() {//create HTML for loading Admin style sheet for table
    $url = get_settings('siteurl');
    $url = $url . '/wp-content/plugins/mf_timetable/mf_timetable_css.css';
    echo '<link rel="stylesheet" type="text/css" href="' . $url . '" />';
}
add_action('admin_head', 'mf_timetable_css');//load admin style sheet for table
add_action('wp_head', 'mf_timetable_css');
$results = mf_database_query();
register_activation_hook(__FILE__,'mf_timetable_install');

$mf_timetable_version="0.1";

function mf_curPageURL() {
 $pageURL = 'http';
 if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
 $pageURL .= "://";
 if ($_SERVER["SERVER_PORT"] != "80") {
  $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
 } else {
  $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
 }
 return $pageURL;
}

function mf_timetable_install () {
   global $wpdb;
   global $mf_timetable_version;

	$table_name = $wpdb->prefix . "mf_timetable";
	if($wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name) {
		$sql = "CREATE TABLE " . $table_name . " (
			  	id mediumint(9) NOT NULL AUTO_INCREMENT,
			  	day text NOT NULL,
				class text NOT NULL,	
			  	location text NOT NULL,
				start text NOT NULL,
				end text NOT NULL,
				teacher text NOT NULL,
			  	cost text NOT NULL,
				category text NOT NULL,
				UNIQUE KEY id (id)
			);";

		require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
		dbDelta($sql);
		
			      $insert = "INSERT INTO " . $table_name .
		            " (day, class, location, start, end, teacher, cost, category) " .
		            "VALUES ('monday','christmas','bethlehem','10.00','12.00','santa','0.00','festival')";

		      $results = $wpdb->query( $insert );

		      add_option("mf_timetable_version", $mf_timetable_version);

		
		
	}


}

function mf_time_admin() {  
     include('mf_timetable_admin.php');  
 }

function mf_timetable_shortcode() {  
     add_shortcode('mf_timetable_display', 'mf_timetable_display');
	
}

function mf_timetable_actions() {  
	add_menu_page("Fuzzy Timetable", "Fuzzy Timetable", 1, "Fuzzy Timetable", "mf_time_admin");  
}  

function mf_database_query() {
	global $wpdb;
	
	$table_name = $wpdb->prefix . "mf_timetable";
	
	//Collect Results---
	if(!isset($_GET['category']) OR $_GET['category']=="all"){
		$query="SELECT * FROM " . $table_name;
	} else {
		$query="SELECT * FROM " . $table_name . " WHERE category= '" . $_GET['category']."'";
	};
	
	$results = $wpdb->get_results($query);
	return $results;
}

function get_category_lists(){
	global $results;
	
	//-------------------
	$cat_array = array();
	
	
	foreach($results as $category_list_results){
	
		
		
		$current_array = get_object_vars($category_list_results);
		$current_day = $current_array['day'];
		//Build Category List---
		array_push($cat_array,$current_array['category']);
		$cat_array = array_unique($cat_array);
		
	}
		
	return $cat_array;
}

function get_day_lists(){
	global $results;
	
	
	$day_array = array();
	
	foreach($results as $category_list_results){
	
		
		
		$current_array = get_object_vars($category_list_results);
		$current_day = $current_array['day'];
	
		
		//Build Day List---
		array_push($day_array,$current_array['day']);
		$day_array = array_unique($day_array);
		
		//-----------------------
	}
		
	
	//Create Normalised List for days
	$day_cat_list = array();
	foreach($day_array as $new_day_array){
		$day_cat_list[$new_day_array] = array();		
	}
	//-------------------------------
	//Build Mulidimensional Day-->Category Array
	$day_array = $day_cat_list;
	foreach($results as $day_category_list_results){
				$current_array = get_object_vars($day_category_list_results);
				$current_day = $current_array['day'];
			array_push($day_array[$current_day],$current_array['category']);
			$day_array[$current_day]=array_unique($day_array[$current_day]);
			
		
	}
	//-------------------------------------------

	
	
	return $day_array;
}

function missing_categorys(){
	$week =  get_day_lists();
	$class_list = get_category_lists();
	foreach($week as $day => $classes){// Creates a multidimensional array, containing all days with unused categories within.
	   
	
	$day_missing[$day]=array_diff($class_list,$classes);
		
	$day_missing[$day]=implode(" no-",$day_missing[$day]);
	
	if (count($day_missing[$day])>0){
		$day_missing[$day]="no-".$day_missing[$day];
	} else {
		$day_missing[$day] = "";
	}
	
			
	}
$missing_cats = $day_missing;
return $missing_cats;
}

function covert_day_output($day){//Converts shortform days to long form for UI display
	switch ($day){
		case mon:
		$return = "Monday";
		break;
		case tue:
		$return = "Tuesday";
		break;
		case wed:
		$return = "Wednesday";
		break;
		case thu:
		$return = "Thursday";
		break;
		case fri:
		$return = "Friday";
		break;
		case sat:
		$return = "Saturday";
		break;
		case sun:
		$return = "Sunday";
		break;
		default:
		$return = $day;
		};
		return $return;	
}
function mf_time_output($start, $end){
	
	$return = date('g:i', mktime($start));
	$return .= " - ";
	$return .= date('g:ia', mktime($end));
	return $return;
}
function mf_timetable_display(){
	//Creates output display for timetable - used in shortcode.
	
	
	//Body Column Widths
	$course_cw = 260; 
	$location_cw = 234;
	$time_cw = 94;
	$teacher_cw = 112;
	$price_cw = 54;
	//Main column Widths
	$day_cw = 140;
	$body_cw = $course_cw+$location_cw+$time_cw+$teacher_cw+$price_cw;
	
	//define column html string
	$columns_html_string = "<col width=\"".$course_cw."\" />";
	$columns_html_string .= "<col width=\"".$location_cw."\" />";
	$columns_html_string .= "<col width=\"".$time_cw."\"/>";
	$columns_html_string .= "<col width=\"".$teacher_cw."\"  />";
	$columns_html_string .="<col width=\"".$price_cw."\"  />";
	
	
	$mf_table_output = "<form id=\"mf_selector\" action=\"";
	$mf_table_output .= mf_curPageURL();
	$mf_table_output .= "\" method=\"get\">";
	$mf_table_output .= "<span id=\"form_title\">show me only</span>";
	$mf_table_output .= "<select name=\"category\">";
	
	
	
	if (isset($_GET['category'])){
		if ($_GET['category']=="all") {
	 		$mf_table_output .= "<option selected value=\"all\">All</option>";
		} else {
			$mf_table_output .= "<option value=\"all\">All</option>";
		};
		if ($_GET['category']=="ballet") {
	 		$mf_table_output .= "<option selected value=\"ballet\">Ballet</option>";
		} else {
			$mf_table_output .= "<option value=\"ballet\">Ballet</option>";
		};
		if ($_GET['category']=="modern") {
	 		$mf_table_output .= "<option selected value=\"modern\">Modern</option>";
		} else {
			$mf_table_output .= "<option value=\"modern\">Modern</option>";
		};
		if ($_GET['category']=="tap") {
	 		$mf_table_output .= "<option selected value=\"tap\">Tap</option>";
		} else {
			$mf_table_output .= "<option value=\"tap\">Tap</option>";
		};
		if ($_GET['category']=="adult") {
	 		$mf_table_output .= "<option selected value=\"adult\">Adult</option>";
		} else {
			$mf_table_output .= "<option value=\"adult\">Adult</option>";
		}
	} else{
		$mf_table_output .= "<option value=\"all\">All</option>";
		$mf_table_output .= "<option value=\"ballet\">Ballet</option>";
		$mf_table_output .= "<option value=\"modern\">Modern</option>";
		$mf_table_output .= "<option value=\"tap\">Tap</option>";
		$mf_table_output .= "<option value=\"adult\">Adult</option>";
	}
	$mf_table_output .= "</select>";
	
	

	
	
	$mf_table_output .= "<input class=\"mf_timetable_ui\" type=\"submit\" value=\"Filter Results\"/>	</form>";

	$missing_categories = missing_categorys();
	global $results;
	
	$current_day = false;
	
	
	//Begin Building Table Output
	//
	//
		
	$mf_table_output .= "<table  class=\"mf_timetable\"> <col width = \"".$day_cw."\"/><col width = \"".$body_cw."\"/>";
	$mf_table_output .= "<thead><tr><td>&nbsp;</td><td><table class=\"subtable\">";
	$mf_table_output .= $columns_html_string;
	$mf_table_output .= "<tr><td class=\"course\">Course</td><td class=\"location\">Location</td><td class=\"time\">Time</td><td class=\"teacher\">Teacher</td><td class=\"cost\">Price</td></tr></table></td></tr></thead>";
	$table_start_count = 0;
	foreach ($results as $table_rows){
	
	
		
	
	if ($current_day != $table_rows->day){
		$day_output = $table_rows->day;
		
		$sub_table_start = "<td><table width=\"".$body_cw."\" style='table-layout:fixed' class=\"subtable\">";
		
		$sub_table_start .= $columns_html_string;
		$sub_table_start .= "<tr  class=\"body_row ".$table_rows->category."\">";
		$sub_table_end = "";
		if ($current_day != false){
			$sub_table_end .= "<tr class=\"line_break\"><td class=\"class\">&nbsp;</td><td class=\"location\">&nbsp;</td><td class=\"time\">&nbsp;</td><td class=\"teacher\">&nbsp;</td><td class=\"cost\"> &nbsp;</td></tr>";
			$sub_table_end .= "</table></td></tr>";
		}
	} else {
			$sub_table_start = "";
			$day_output = "";
			$sub_table_end = "";
	}
	
	$mf_table_output .= $sub_table_end;
	
	
	if ($day_output!=""){
		$table_start_count++;
	$mf_table_output .= "<tr class=\"".$missing_categories[$day_output]."\"><td class=\"day\">".covert_day_output($day_output)."</td>".$sub_table_start;
	} else {
		$mf_table_output .=	"<tr class=\" body_row ".$table_rows->category."\">";
	}
 	


	if ($current_day != $table_rows->day){
	$current_day = $table_rows->day;
	
	}
	
	$mf_table_output .=	"<td class=\"class\">".$table_rows->class;
	$mf_table_output .=	"</td><td class=\"location\">".$table_rows->location;
	
	$mf_table_output .=	"</td><td class=\"time\">";
	$mf_table_output .= mf_time_output($table_rows->start,$table_rows->end);
	$mf_table_output .=	"</td><td class=\"teacher\">".$table_rows->teacher;
	$mf_table_output .=	"</td><td class=\"cost\"> £".$table_rows->cost;
	
	$mf_table_output .=	"</td></tr>";
	};
	
	$mf_table_output .= "<tr class=\"last_break\"><td class=\"class\">&nbsp;</td><td class=\"location\">&nbsp;</td><td class=\"time\">&nbsp;</td><td class=\"teacher\">&nbsp;</td><td class=\"cost\"> &nbsp;</td></tr>";
	$mf_table_output .= "</table></td></tr></table>";
	

	
	echo $mf_table_output;

}

function mf_jquery_launch(){
	wp_enqueue_script('jquery');
	wp_enqueue_script('mf_timetable_UI', WP_PLUGIN_URL . '/mf_timetable/mf_timetable_UI.js');
	
}

add_shortcode('mf_timetable_display', 'mf_timetable_display');
add_action('admin_menu', 'mf_timetable_actions');
add_action('init','mf_jquery_launch');
?>